﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Minio.DataModel.Args;
using Minio;
using Newtonsoft.Json;
using D.Medicalcare.ErrorCode;

namespace I_FileUpload.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class DoctorController : ControllerBase
    {
        private readonly IMinioClient _minioClient;
        private string bucketName = "sheepimages";
        private string host = "10.223.2.12:9000";
        public DoctorController()
        {
            _minioClient = new MinioClient()
                           .WithEndpoint(host)
                           .WithCredentials("admin", "admin123")
                           .WithSSL(false)
                           .Build();

        }

        /// <summary>
        /// 列出所有的桶
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> ListBuckets()
        {
            var buckets = await _minioClient.ListBucketsAsync().ConfigureAwait(false);
            return Ok(buckets);
        }

        /// <summary>
        /// 上传单个文件
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<APIResult<string>> UploadFile(IFormFile file)
        {
            APIResult<string> result = new APIResult<string>() { Code = APIEnum.Failed };
            //检查桶是否存在
            var beArgs = new BucketExistsArgs().WithBucket(bucketName);
            bool found = await _minioClient.BucketExistsAsync(beArgs);
            //如果桶不存在则创建桶
            if (!found)
            {
                var mbArgs = new MakeBucketArgs().WithBucket(bucketName);
                await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);
            }

            //获取文件名
            var objectName = file.FileName;

            //使用流数据上传文件
            var putArgs = new PutObjectArgs()
                .WithBucket(bucketName)
                .WithObject(objectName)
                .WithStreamData(file.OpenReadStream())
                .WithContentType(file.ContentType)
                .WithObjectSize(file.Length);
            await _minioClient.PutObjectAsync(putArgs).ConfigureAwait(false);

            var getArgs = new PresignedGetObjectArgs()
                .WithBucket(bucketName)
                .WithObject(objectName)
                .WithExpiry(7200);

            
            var url = await _minioClient.PresignedGetObjectAsync(getArgs).ConfigureAwait(false);
            var presignedUrl = $"http://{host}/{bucketName}/{objectName}";

            url = presignedUrl;
            result.Code = APIEnum.Success;
            result.Data = url;
            return result;
        }
        /// <summary>
        /// 上传多个文件
        /// </summary>
        /// <param name="formFiles"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<IActionResult> UploadFiles(IFormFileCollection formFiles)
        {
            //检查桶是否存在
            var beArgs = new BucketExistsArgs().WithBucket(bucketName);
            bool found = await _minioClient.BucketExistsAsync(beArgs);

            //如果不存在则创建桶
            if (!found)
            {
                var mbArgs = new MakeBucketArgs().WithBucket(bucketName);
                await _minioClient.MakeBucketAsync(mbArgs).ConfigureAwait(false);

            }

            var formFileList = new List<string>();
            foreach (var formFile in formFiles)
            {
                using var stream = formFile.OpenReadStream();
                //获取文件名称
                var objestName = formFile.FileName;
                formFileList.Add(objestName);
                //使用流数据上传文件
                var putArgs = new PutObjectArgs()
                    .WithBucket(bucketName)
                    .WithObject(objestName)
                    .WithStreamData(stream)
                    .WithStreamData(stream)
                    .WithContentType(formFile.ContentType)
                    .WithObjectSize(stream.Length);

                await _minioClient.PutObjectAsync(putArgs).ConfigureAwait(false);

            }
            return Ok(formFileList);
        }
    }
}